class PlacesController < ApplicationController
  before_filter :login_required, :only => [:new]
  require 'rubygems'
  require 'httparty'
  require "rexml/document"
  require "oauth/consumer"
  include REXML
  include HTTParty

  def index
  end

  def search

    if params[:lat].blank? && params[:search_where].blank? && params[:search_what].blank?
      flash[:notice] = "Searchfields empty."
      redirect_to root_url
    end
    
    qype = Qype::Client.new(MyQype::API_KEY, MyQype::API_SECRET)

    if params[:near_me] == "1" && !params[:lat].blank? && !params[:lng].blank?
      #http://api.qype.com/v1/positions/47.70,8.64/places?show=Pizza%20&consumer_key=5FVNdon5fzYzCRGwcPc57g
      #request = qype.get("http://api.qype.com/v1/positions/#{params[:lat]},#{params[:lng]}/places?show=#{params[:search_what]}")
      #@places = Qype::Place.parse(request.body)
      @places = qype.nearby_places(params[:lat], params[:lng], {:show => "restaurant, #{params[:search_what]}"})
      session[:my_location] = {:lat => params[:lat], :lng => params[:lng]}
      puts @places
    else
      @places = qype.search_places("restaurant, #{params[:search_what]}", params[:search_where] )
    end
    # For paging see result of http://api.qype.com/v1/places?show=restaurant&in=Schaffhausen&consumer_key=5FVNdon5fzYzCRGwcPc57g

  end

  def detail
    if params[:id].nil? || params[:id].empty?
      redirect_to root_url  
    end
    qype = Qype::Client.new(MyQype::API_KEY, MyQype::API_SECRET)
    @place = qype.get_place(params[:id])
    @place_id = @place.place_id
  end

  def results
    qype = Qype::Client.new(MyQype::API_KEY, MyQype::API_SECRET)

    case  params[:type]
      when "by_name"
        @places = qype.search_places('restaurant', params[:search_string] )
      when "by_address"
        #TODO: implement
      when "near_me"
        #TODO: implement
    end

  end

  def new
    @place = Place.new()
    @place.build_address
  end

  def create
    @place = Place.new(params[:place])
    if @place.valid?
      flash[:notice] = "Successfully created place."
      redirect_to root_url
    else
      render :action => 'new'
    end

  end

  def photos
    qype = Qype::Client.new(MyQype::API_KEY, MyQype::API_SECRET)
    @place = qype.get_place(params[:id])
    @place_id = @place.place_id
  end
end
